<?php

/**
 * 评论模块
 * @version $Id: Comment.php 567 2015-02-05 11:52:51Z karson $
 */
class CommentModel Extends Model {

    public $key = "";

    /**
     * 构造函数
     */
    public function __construct() {
        parent::__construct();
    }

    public function get($id) {
        return $this->db->one("SELECT * FROM {pre}comment WHERE id = ?", array($id));
    }

    /**
     * 读取评论列表
     */
    public function lists($thread_id, $offset = 0) {
        $orderby = " likes DESC,createtime DESC";
        $where = "status = 'normal'";
        $where .= " AND thread_id = " . intval($thread_id);
        if ($offset) {
            $where .= " AND id < " . intval($offset);
        }
        $commentlist = $this->db->all("SELECT * FROM {pre}comment WHERE {$where} ORDER BY {$orderby} LIMIT 10");
        foreach ($commentlist as $k => & $v) {
            unset($v['status'], $v['weigh']);
        }
        $this->user->renderdata($commentlist);
        return $commentlist ? $commentlist : array();
    }

    /**
     * 发表评论
     */
    public function post($content, $thread_id) {
        $threadinfo = $this->thread->get($thread_id);
        if ($threadinfo) {
            $params = array(
                'user_id' => $this->user->id,
                'thread_id' => $thread_id,
                'thread_user_id' => $threadinfo['user_id'],
                'content' => $content,
                'createtime' => time(),
                'status' => 'normal'
            );
            $this->db->insert("{pre}comment", $params);
            $comment_id = $this->db->id();
            if ($comment_id) {
                $this->db->update("{pre}thread", array('comments' => ':comments + 1', 'updatetime' => time()), array('id' => $thread_id));
                return $comment_id;
            } else {
                return 0;
            }
        } else {
            return 0;
        }
    }

}
